import frappe
from frappe.utils import get_link_to_form
from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_invoice


@frappe.whitelist()
def create_purchase_invoice(docname):
    #获取委外采购明细，委外入库明细->委外订单明细->委外订单->委外采购明细
    sr = frappe.qb.DocType('Subcontracting Receipt')
    sri = frappe.qb.DocType('Subcontracting Receipt Item')
    soi = frappe.qb.DocType('Subcontracting Order Item')
    poi = frappe.qb.DocType('Purchase Order Item')
    query_result = frappe.qb.from_(sr
        ).join(sri
        ).on(sr.name == sri.parent
        ).join(soi
        ).on(sri.subcontracting_order_item == soi.name
        ).join(poi
        ).on(poi.name == soi.purchase_order_item
        ).where(sri.parent == docname
        ).select(
            poi.parent.as_('po'), 
            poi.name.as_('poi_name'), 
            sri.qty, 
            sr.supplier_warehouse
        ).run(as_dict = True)
    po_dict = {}
    for row in query_result:
        po_item_dict = po_dict.setdefault(row.po, row)
        po_item_dict[row.get('poi_name')] = row['qty']
    invoice_list = []    
    for (po, item_dict) in po_dict.items():
        #调用标准的采购订单下推发票功能
        invoice_doc = make_purchase_invoice(source_name = po)
        #只保留本次入库行, 同步委外入库数量
        items = []
        for item in invoice_doc.items:
            poi_qty = item_dict.get(item.po_detail, 0)
            if poi_qty:
                item.qty = poi_qty
                items.append(item)
        invoice_doc.is_return = frappe.db.get_value('Subcontracting Receipt', docname, 'is_return')    
        invoice_doc.subcontracting_receipt = docname        
        invoice_doc.items = items
        invoice_doc.update_stock = 1
        invoice_doc.supplier_warehouse = po_item_dict.supplier_warehouse
        invoice_doc.run_method("calculate_taxes_and_totals")
        invoice_doc.insert(ignore_permissions = True)
        invoice_list.append(get_link_to_form("Purchase Invoice", invoice_doc.name))
    return ','.join(invoice_list)

